using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TCEntity;

namespace TCDbService
{
  public class ImageService
  {
    readonly TCDbContext _context;
    readonly AccountService _account;
    public ImageService(TCDbContext context, AccountService accountService)
    {
      _context = context;
      _account = accountService;
    }
    public async Task<int> UploadAsync(User user, byte[] picture)
    {
      var member = await _account.LoginAsync(user);
      if (picture == null || !picture.Any()) throw new ArgumentException("上传的图像为空。");
      Image image = new()
      {
        Picture = picture,
        UploadTime = DateTime.Now,
        Username = member.Username
      };
      _context.Add(image);
      await _context.SaveChangesAsync();
      return image.Id;
    }
    async Task<List<Image>> FindAsync(System.Linq.Expressions.Expression<Func<Image, bool>> expression)
    {
      var images = await _context.Images.Where(expression).ToListAsync();
      //if (!images.Any()) throw new ArgumentException("指定的图片不存在。");
      return images;
    }

    public async Task<List<Image>> DownloadAsync(User user)
    {
      var member = await _account.LoginAsync(user);
      return await FindAsync(image => image.Username == member.Username);
    }
    public async Task<List<Image>> DownloadAsync(User user, DateTime time)
    {
      var member = await _account.LoginAsync(user);
      return await FindAsync(image => image.Username == member.Username && image.UploadTime.Date == time.Date);
    }
    public async Task<Image> DownloadAsync(User user, int id)
    {
      await _account.LoginAsync(user);
      var image = await _context.Images.FindAsync(id);
      if (image == null) throw new ArgumentException("指定的图片不存在。");
      return image;
    }
    public async Task DeleteAsync(User user, int id)
    {
      var image = await DownloadAsync(user, id);
      _context.Remove(image);
      await _context.SaveChangesAsync();
    }
    public async Task DeleteAsync(User user)
    {
      var images = await DownloadAsync(user);
      _context.RemoveRange(images);
      await _context.SaveChangesAsync();
    }

    public async Task<List<Image>> FilterAsync(int[] order)
    {
      var images = new List<Image>();
      var cI = await _context.Images.ToListAsync();
      foreach (int i in order)
      {
        var queryResult = cI.Where(p => p.ImageCategory[i]==1);
        List<Image> temp = queryResult.ToList();
        images.AddRange(temp);
      }
      images.AddRange(cI.Where(p => p.ImageCategory.All(b => b == 0)));
      images.AddRange(cI.Where(p => p.ImageCategory.All(b => b == 1)));
      return images;
    }

  }
}
